#include "piece.hpp"
#include <algorithm>

namespace Tetris {

Piece::Piece(BlockType type) 
    : m_tetromino(Tetromino::getAllTetrominos().at(type))
    , m_position(BOARD_WIDTH / 2 - 2, BOARD_HIDDEN_TOP - 1)
    , m_rotationState(0)
{
    // 如果是I或者O方块，调整初始位置使其居中
    if (type == BlockType::I) {
        m_position.x = BOARD_WIDTH / 2 - 2;
    }
    else if (type == BlockType::O) { // 冗余？
        m_position.x = BOARD_WIDTH / 2 - 1; // O方块小些
    }
    else {
        m_position.x = BOARD_WIDTH / 2 - 1;
    }

}


std::vector<Point> Piece::getAbsoluteCoords() const {
    std::vector<Point> coords;
    const auto& currentShape = m_tetromino.m_shapes[m_rotationState];
    for (const auto& p : currentShape) {
        coords.push_back(m_position + p);
    }
    return coords;
}


void Piece::move(int dx, int dy) {
    m_position.x += dx;
    m_position.y += dy;
}


void Piece::rotate() {
    m_rotationState = (m_rotationState + 1) % m_tetromino.m_shapes.size();
}


void Piece::unrotate() {
    m_rotationState = (m_rotationState - 1 + m_tetromino.m_shapes.size()) % m_tetromino.m_shapes.size();
}


void Piece::draw(WINDOW* win, int offset_x, int offset_y, bool is_ghost) const {
    const auto& currentShape = m_tetromino.m_shapes[m_rotationState];
    int draw_color_id = is_ghost ? COLOR_PAIR_GHOST : m_tetromino.m_colorId;

    wattron(win, COLOR_PAIR(draw_color_id));
    for (const auto& p : currentShape) {
        int target_y = offset_y + (m_position.y + p.y - BOARD_HIDDEN_TOP) + 1;
        int target_x = offset_x + (m_position.x + p.x) * 2 + 1;

        if (m_position.y + p.y >= BOARD_HIDDEN_TOP) {
            mvwaddch(win, target_y, target_x, '[');
            mvwaddch(win, target_y, target_x + 1, ']');
        }
        else {
            mvwprintw(win, target_y, target_x, "[]");
        }
    }
    wattroff(win, COLOR_PAIR(draw_color_id));
}


void Piece::clear(WINDOW* win, int offset_x, int offset_y) const {
    const auto& currentShape = m_tetromino.m_shapes[m_rotationState];
    // 用空方块的背景色覆盖
    wattron(win, COLOR_PAIR(COLOR_PAIR_EMPTY));
    for (const auto& p : currentShape) {
        mvwprintw(win, offset_y + m_position.y + p.y, (offset_x + m_position.x + p.x) * 2, "  ");
    }
    wattroff(win, COLOR_PAIR(COLOR_PAIR_EMPTY)); 
}

} // namespace Tetris  
